import util.lib as lib
import util.mydecorator as mydecorator

import pandas as pd


mydict = {}

# 调整单个数据
def built_cell(df, label = "adjusted_profit"):
    # 取整年数据
    df = df[df['ses'].str.len() == 4]

    ret = None
    for stock in df["name"].drop_duplicates():

        tmp = df[df['name']==stock][[label,'ses']]
        tmp = tmp.set_index("ses")

        t1 = tmp[[label]].T
        t1["stock"] = stock
        
        if ret is None:
            ret = t1
        else:
            ret = pd.concat([ret, t1], ignore_index=True)
            
    return ret


@mydecorator.calTime
def job():
    writer = pd.ExcelWriter(lib.data_path +'stock_finance_cal.xlsx')

    data = lib.lib_get_finance_data()

    new_df = pd.DataFrame()
    for key, df in data.items():
        new_df = pd.concat([new_df, df], ignore_index=True)

    new_df.to_excel(writer, sheet_name="finance_data")

    finance_list = [
        "total_operating_revenue",  #  营业总收入
        "net_profit", #净利润
        "adjusted_profit",  # 扣非净利润
        "roe",
        "gross_profit_margin", # 毛利率
        "net_profit_margin",  # 净利率
        "liability_on_asset_ratio", # 资产负债率
        "net_operate_cash_flow", # 经营活动产生的现金流量净额
        "inc_total_revenue_year_on_year", #  营业总收入同比增长率(%)
        "inc_net_profit_to_shareholders_year_on_year",  # 归属母公司股东的净利润同比增长率(%)
        ]

    for label in finance_list:
        print(label)
        df = built_cell(new_df, label)
        df.to_excel(writer, sheet_name=label)

    writer.save()
    return


if __name__ == "__main__":
    job()